package com.vvvtimes.demo.util.endecrypt;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidParameterSpecException;

@Slf4j
public class BcBfUtil {

    private static final BouncyCastleProvider provider;

    /**
     * 偏移变量，固定占8位字节
     */
    private final static String IV_PARAMETER = "1234567890123456";

    /**
     * Blowfish加密
     */
    public static byte[] encrypt(byte[] data, byte[] password) {
        if (data == null)
            return null;
        try {
            Key secretKey = new SecretKeySpec(password,"Blowfish");
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding",provider);

            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(data);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * Blowfish解密解密字符串
     */
    public static byte[] decrypt(byte[] data, byte[] password) {
        if (data == null)
            return null;
        try {
            Key secretKey = new SecretKeySpec(password,"Blowfish");
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding",provider);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(data);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }



    /**
     * byte数组转十六进制
     *
     * @param bytes
     * @return
     */
    public static String byte2HexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        if (bytes != null) {
            for (Byte b : bytes) {
                hex.append(String.format("%02X", b.intValue() & 0xFF));
            }
        }
        return hex.toString();
    }

    //测试
    public static void main(String[] args) throws Exception {
        String source = "admin测试信息1234!@#$%^&*()_+";
        System.out.println("原  文: " + source);
        String password = "password";
        byte[] encryptDataBytes = encrypt(source.getBytes("utf-8"), password.getBytes("utf-8"));
        String encryptData = byte2HexString(encryptDataBytes);
        System.out.println("加密后: " + encryptData);
        byte[] decryptDataBytes = decrypt(encryptDataBytes, password.getBytes("utf-8"));
        String decryptData = new String(decryptDataBytes, "utf-8");
        System.out.println("解密后: " + decryptData);
    }

    static {
        provider = new BouncyCastleProvider();
    }
}
